<!--
 * @Author: Liz.Zheng
 * @Date: 2021-10-27 13:44:24
 * @LastEditTime: 2023-02-16 10:17:02
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 编辑、增加流水账号
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-drawer
    :title="title"
    :maskClosable="false"
    :visible="visible"
    :destroyOnClose="true"
    :width="$store.getters.isMobile ? 350 : 450"
    :body-style="{ paddingBottom: '80px' }"
    @close="closeModal"
  >
    <a-form layout="vertical">
      <a-form-item label="条目名称" v-bind="validateInfos.name">
        <a-input placeholder="请输入条目名称" v-model:value="modelRef.name" />
      </a-form-item>
      <a-form-item label="收款公司" v-bind="validateInfos.company">
        <a-input
          placeholder="请输入收款公司"
          v-model:value="modelRef.company"
        />

        <!-- <a-select
          :value="modelRef.company"
          show-search
          placeholder="请输入收款公司"
          :default-active-first-option="false"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
          :options="companyData"
          @search="handleCompanySearch"
          @change="handleCompanyChange"
          @blur="handleCompanyBlur"
        >
        </a-select> -->
      </a-form-item>
      <a-form-item label="开户银行" v-bind="validateInfos.bank">
        <a-input placeholder="请输入开户银行" v-model:value="modelRef.bank" />
      </a-form-item>
      <a-form-item label="银行账号" v-bind="validateInfos.bank_account">
        <a-input
          placeholder="请输入银行账号"
          v-model:value="modelRef.bank_account"
        />
      </a-form-item>
      <a-form-item label="总分类账科目" v-bind="validateInfos.subject">
        <a-input
          placeholder="请输入总分类账科目"
          v-model:value="modelRef.subject"
        />
      </a-form-item>
      <a-form-item label="应用楼宇" v-bind="validateInfos.build">
        <TreeSelect
          v-model:value="modelRef.build"
          :tree-data="villiageData"
          tree-checkable
          allow-clear
          placeholder="请选择应用楼宇"
          :labelInValue="true"
        ></TreeSelect>
      </a-form-item>
      <a-form-item label="状态" v-bind="validateInfos.status">
        <a-switch
          :checkedValue="1"
          :unCheckedValue="0"
          v-model:checked="modelRef.status"
          checked-children="开启"
          un-checked-children="关闭"
        />
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { computed, defineComponent, reactive, ref, toRaw, watch } from "vue";
import { Form, message, TreeSelect } from "ant-design-vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
const useForm = Form.useForm;

export default defineComponent({
  name: "EditRunAccount",
  components: { TreeSelect },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, context) {
    /**
     * @description: 标题显示
     */
    const title = computed(() => {
      return props.id ? "编辑收支账户" : "新增收支账户";
    });

    /**
     * @description: 触发关闭
     */
    const closeModal = () => {
      context.emit("closeAccount");
    };

    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      name: "",
      company: undefined,
      bank: "",
      bank_account: "",
      subject: "",
      build: [],
      status: 1,
    });
    // 获取公司列表
    const companyData = ref([]);
    let timeout = null;
    let currentValue = "";
    const handleCompanySearch = (val) => {
      // console.log(val);
      getCompanyData(val, (result) => (companyData.value = result));
    };
    const handleCompanyChange = (val) => {
      modelRef.company = val;
    };
    const handleCompanyBlur = () => {
      if (currentValue && !modelRef.company) {
        modelRef.company = currentValue;
      }
    };
    const getCompanyData = (value, callback) => {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      currentValue = value;
      const getResult = () => {
        request.post("/org", "/account/companyList", { keywords: value }).then(
          (res) => {
            if (currentValue === value) {
              let result = [];
              if (res.list) {
                result = res.list.map((item) => ({
                  value: item,
                  label: item,
                }));
              }
              callback(result);
            }
          }
        );
      };
      timeout = setTimeout(getResult, 300);
    };
    //获取项目和楼宇列表
    const villiageData = ref([]);

    const getVilliageData = () => {
      request.get("/org", "/build/villageAndBuildList").then((res) => {
        villiageData.value = utils.transformVilliageData(res.villageList) || [];
      });
    };

    /**
     * @description: 验证规则
     */
    const rulesRef = reactive({
      name: [{ required: true, message: "条目名称为必填项" }],
      company: [{ required: true, message: "收款公司为必填项" }],
      bank: [{ required: true, message: "开户银行为必填项" }],
      bank_account: [{ required: true, message: "	银行账号为必填项" }],
      build: [{ required: true, message: "楼宇为必填项" }],
      status: [{ required: true }],
    });

    /**
     * @description: 创建表单
     */
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      validate()
        .then(() => {
          let params = { ...toRaw(modelRef), needMsg: true };
          params.build = utils.transformBuildData(params.build);
          console.log(params);
          const success = (res) => {
            message.success(res.msg || "保存成功");
            context.emit("success");
          };
          if (props.id) {
            params.id = props.id;
            request.put("/org", "/manage/account", params).then((res) => success(res));
          } else {
            request.post("/org", "/manage/account", params).then((res) => success(res));
          }
        })
        .catch((err) => {
          console.log("error", err);
        });
    };

    /**
     * @description: 获取编辑信息
     */
    const getEditInfo = () => {
      request.get("/org", "/manage/account/get", { id: props.id }).then((res) => {
        const { detail } = res;
        setModelRef({
          name: detail.name,
          company: detail.company,
          bank: detail.bank,
          bank_account: detail.bank_account,
          subject: detail.subject,
          build: utils.transformBuildData(detail.build),
          status: detail.status,
        });
      });
    };

    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };

    /**
     * @description: 初始化
     */
    const init = () => {
      getVilliageData();
      if (props.id) {
        getEditInfo();
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          // 打开时初始化数据
          init();
        } else {
          // 关闭时重置数据
          resetFields();
        }
      }
    );
    return {
      title,
      closeModal,
      validateInfos,
      companyData,
      handleCompanySearch,
      handleCompanyChange,
      handleCompanyBlur,
      villiageData,
      resetFields,
      modelRef,
      onSubmit,
    };
  },
});
</script>
